<?php

namespace app\api\controller;

/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/11/23
 * Time: 19:22
 */

/**
 * 与用户中心通信api
 * Class User
 * @package app\api\controller
 */
class User
{
    public $client;

    public function __construct()
    {
        $this->client = new Client();
    }
    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|mixed
     */
    public function login($username = '', $password = '')
    {
        try {
            $re = $this->getLoginStatus($username, $password);
            if ($re['result'] == true) {
                // 自动登录
                $this->auto_login($re['msg']);
            }
            return $re;
        } catch (\HttpRequestException $exception) {
            return ['result' => false, 'msg' => $exception->getMessage()];
        }

    }

    /**
     * 自动登录
     * @param mixed $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     */
    public function auto_login($user, $rememberme = false)
    {
        // 记录登录
        $auth = array(
            'adminid' => $user['id'],
            'username' => $user['username'],
            'depar_id' => $user['depar_id'],
//            'depar_name' => !empty($user['depar']['name']) ? $user['depar']['name'] : '',
//            'dq_id' => $user->dq_id,
//            'group_id' => $user->group_id,
//            'ygroup_id' => empty($user->ygroup_id) ? '' : $user->ygroup_id,
//            'avr' => $user->headimgurl,
//            'qudao' => $user->qudao
        );
        session('admin_user', $auth);
        // 记住登录
        if ($rememberme) {
            $signin_token = $user->username . $user->id;
            cookie('aid', $user->id, 24 * 3600 * 7);
            cookie('signin_token', ($signin_token), 24 * 3600 * 7);
        }
    }

    /**
     *  用户中心登录状态
     * @param string $username
     * @param string $password
     * @param bool $json true是json false是数组
     * @return mixed|string
     */
    public function getLoginStatus($username = '', $password = '', $json = false)
    {
        $data = $this->client->Client('Login','login',[
            'username'=>$username,
            'password'=>$password
        ]);
        return $json ? json_decode($data, true) : $data;
    }
}